package com.cy.myblog.action.login;

import com.cy.myblog.action.BaseAction;
import com.cy.myblog.model.TloginInfo;
import com.cy.myblog.service.LoginInfoServiceI;
import com.cy.myblog.util.ImageUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;

@Controller
@Scope("prototype")
@ParentPackage("json-default")
@Namespace("/")
@Action(value = "codeAction")
@Result(name="image",type="stream",params={"inputName","is"})
public class CodeAction extends BaseAction{

	private InputStream is;
	private String uuid;
	
	private LoginInfoServiceI loginInfoService;
	
	public LoginInfoServiceI getLoginInfoService() {
		return loginInfoService;
	}

	@Autowired
	public void setLoginInfoService(LoginInfoServiceI loginInfoService) {
		this.loginInfoService = loginInfoService;
	}

	public String imageCode() {
		
		Map<String, BufferedImage> map = ImageUtils.getImage();
		String code = map.keySet().iterator().next();
		
		if(uuid != null || !"".equals(uuid)){
			TloginInfo info1 = loginInfoService.getById(uuid);
			if(info1 == null){
				TloginInfo info = new TloginInfo();
				info.setId(uuid);
				info.setCode(code);
				info.setLoginTime(new Date());
				loginInfoService.save(info);
			}else{
				info1.setCode(code);
				loginInfoService.update(info1);
			}
			
		}
		
		BufferedImage image = map.get(code);
		try {
			is = ImageUtils.imageToStream(image);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return "image";
	}

	public InputStream getIs() {
		return is;
	}

	public void setIs(InputStream is) {
		this.is = is;
	}

	public String getUuid() {
		return uuid;
	}

	public void setUuid(String uuid) {
		this.uuid = uuid;
	}
	
}
